package com.lohit.dbtest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import com.lohit.dbtest.service.ScheduleClient;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;

import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

@SuppressLint("SimpleDateFormat")
public class CreateAppointmentActivity extends Activity {

	Context context = CreateAppointmentActivity.this;
	public static final String PREFS_APPOINTMENTS = "AppointmentDetails";
	// Calendar c1 = Calendar.getInstance();

		final String s1 = "09:30 AM";
	
		final String s2 = "10:00 AM";
		
		final String s3 = "10:30 AM";
		
		final String s4 = "11:00 AM";
		
		final String s5 = "11:30 AM";
		
	
		final String s6 = "12:00 PM";
	
		final String s7 = "12:30 PM";
	
		
		final String s8 = "01:00 PM";
		
		final String s9 = "01:30 PM";
	
		final String s10 = "03:00 PM";
	
		final String s11 = "03:30 PM";
	
		final String s12 = "04:00 PM";
	
		final String s13 = "04:30 PM";
	
		final String s14 = "05:00 PM";
	
		final String s15 = "05:30 PM";
	
		final String s16 = "06:00 PM";
	
		final String s17 = "06:30 PM";
	
		final String s18 = "07:00 PM";
	
		final String s19 = "07:30 PM";
		final String s20 = "08:00 PM";

	SendSMS mSender = new SendSMS();
	Date dateObj;

	String d1;

	String selectedTime;

	String timeDB;

	public static final String PREFS_NAME = "LoginCredentials";

	DbController controller = new DbController(this);

	String Value;

	private ScheduleClient scheduleClient;

	EditText illnessET, dateET, timeET, locET;

	static final int DATE_DIALOG_ID = 1;

	static final int TIME_DIALOG_ID = 0;

	Button createBtn, cancelBtn;

	int mYear, mMonth, mDay;

	int hour, minute;

	String phoneNumber;

	Spinner timeSpinner;

	String cause, date, time, location, status = "0";

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_appointment);

		scheduleClient = new ScheduleClient(this);

		scheduleClient.doBindService();

		final Calendar c = Calendar.getInstance();

		mYear = c.get(Calendar.YEAR);

		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		Bundle extras = getIntent().getExtras();

		Value = extras.getSerializable("id").toString();

		phoneNumber = extras.getSerializable("phone").toString();

		Log.d("mobile_number", phoneNumber);

		illnessET = (EditText) findViewById(R.id.illnessEditText);
		dateET = (EditText) findViewById(R.id.dateEditText);
		locET = (EditText) findViewById(R.id.locationEditText);

		// spinner = (Spinner) findViewById(R.id.spinner1);

		// timeET = (EditText) findViewById(R.id.timeEditText);

		createBtn = (Button) findViewById(R.id.createButton);
		cancelBtn = (Button) findViewById(R.id.cancelButton);
		timeSpinner = (Spinner) findViewById(R.id.timeSpinner);
		cancelBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent i = new Intent(CreateAppointmentActivity.this,
						Main.class);

				startActivity(i);

			}
		});

		/*
		 * timeET.setOnTouchListener(new View.OnTouchListener() {
		 * 
		 * @Override public boolean onTouch(View v, MotionEvent event) {
		 * 
		 * showDialog(TIME_DIALOG_ID); return true;
		 * 
		 * } });
		 */
		dateET.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				showDialog(DATE_DIALOG_ID);
				return true;

			}
		});

		timeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

				selectedTime = timeSpinner.getSelectedItem().toString();

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});

		createBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				cause = illnessET.getText().toString();

				date = dateET.getText().toString();

				location = locET.getText().toString();

				// time = timeET.getText().toString();

				boolean status = validateInputs(cause, date, selectedTime,
						location);

				if (status) {

					appoint();
				}

			}
		});

	}

	public boolean validateInputs(String cause, String date, String time,
			String location) {

		if (date.equals("") || date.length() == 0) {

			Toast.makeText(this, "Please enter appointment date ",
					Toast.LENGTH_SHORT).show();

			dateET.requestFocus();

			return false;

		}

		if (time.equals("") || time.length() == 0) {

			Toast.makeText(this, "Please enter Patient's age ",
					Toast.LENGTH_SHORT).show();

			timeET.requestFocus();

			return false;

		}

		return true;

	}

	@SuppressLint("SimpleDateFormat")
	public void appoint() {

		SharedPreferences app_settings = getSharedPreferences(
				PREFS_APPOINTMENTS, 0);

		String pid = Value;

		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm aa");

		if (selectedTime.equals(s1)) {
			Toast.makeText(context, "slot1 if block", Toast.LENGTH_LONG).show();

			int im = controller.setSlot(date, "slot1");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			} else {

				Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
			}

		} else if (selectedTime.equals(s2)) {
			Toast.makeText(context, "slot2 if block", Toast.LENGTH_LONG).show();

			int im = controller.setSlot(date, "slot2");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
			}

		} else if (selectedTime.equals(s3)) {
			Toast.makeText(context, "slot3 if block", Toast.LENGTH_LONG).show();

			int im = controller.setSlot(date, "slot3");
			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
			}

		} else if (selectedTime.equals(s4)) {

			Toast.makeText(context, "slot4 if block", Toast.LENGTH_LONG).show();

			int im = controller.setSlot(date, "slot4");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
			}

		} else if (selectedTime.equals(s5)) {
			Toast.makeText(context, "slot5 if block", Toast.LENGTH_LONG).show();

			int im = controller.setSlot(date, "slot5");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		} else if (selectedTime.equals(s6)) {
			Toast.makeText(context, "slot6 if block", Toast.LENGTH_LONG).show();

			int im = controller.setSlot(date, "slot6");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		} else if (selectedTime.equals(s7)) {
			Toast.makeText(context, "slot7 if block", Toast.LENGTH_LONG).show();

			int im = controller.setSlot(date, "slot7");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		} else if (selectedTime.equals(s8)) {
			Toast.makeText(context, "slot8 if block", Toast.LENGTH_LONG).show();

			int im = controller.setSlot(date, "slot8");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		}

		else if (selectedTime.equals(s9)) {
			Toast.makeText(context, "slot9 if block", Toast.LENGTH_LONG).show();

			int im = controller.setSlot(date, "slot9");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		}

		else if (selectedTime.equals(s10)) {
			Toast.makeText(context, "slot10 if block", Toast.LENGTH_LONG)
					.show();

			int im = controller.setSlot(date, "slot10");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		}

		else if (selectedTime.equals(s11)) {
			Toast.makeText(context, "slot15 if block", Toast.LENGTH_LONG)
					.show();

			int im = controller.setSlot(date, "slot11");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		}

		else if (selectedTime.equals(s12)) {
			Toast.makeText(context, "slot12 if block", Toast.LENGTH_LONG)
					.show();

			int im = controller.setSlot(date, "slot12");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		} else if (selectedTime.equals(s13)) {
			Toast.makeText(context, "slot13 if block", Toast.LENGTH_LONG)
					.show();

			int im = controller.setSlot(date, "slot13");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		}

		else if (selectedTime.equals(s14)) {
			Toast.makeText(context, "slot14 if block", Toast.LENGTH_LONG)
					.show();

			int im = controller.setSlot(date, "slot14");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		} else if (selectedTime.equals(s15)) {
			Toast.makeText(context, "slot15 if block", Toast.LENGTH_LONG)
					.show();

			int im = controller.setSlot(date, "slot15");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		}

		else if (selectedTime.equals(s16)) {
			Toast.makeText(context, "slot16 if block", Toast.LENGTH_LONG)
					.show();

			int im = controller.setSlot(date, "slot16");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		} else if (selectedTime.equals(s17)) {
			Toast.makeText(context, "slot17 if block", Toast.LENGTH_LONG)
					.show();

			int im = controller.setSlot(date, "slot17");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		} else if (selectedTime.equals(s18)) {
			Toast.makeText(context, "slot18 if block", Toast.LENGTH_LONG)
					.show();

			int im = controller.setSlot(date, "slot18");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		} 
		
		else if (selectedTime.equals(s19)) {
			Toast.makeText(context, "slot19 if block", Toast.LENGTH_LONG)
					.show();

			int im = controller.setSlot(date, "slot19");

			if (im == 1) {

				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		}
		else if (selectedTime.equals(s20)) {
			Toast.makeText(context, "slot20 if block", Toast.LENGTH_LONG)
			.show();
			
			int im = controller.setSlot(date, "slot20");
			
			if (im == 1) {
				
				Toast.makeText(context,
						"Appointment Created at" + selectedTime,
						Toast.LENGTH_LONG).show();
			}
		}

		else {
			Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();

		}

		try {
			
			dateObj = sdf.parse(date + " " + selectedTime);

			SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");

			
			timeDB = sdf2.format(dateObj);

		
		} catch (ParseException e1) {

		
			
			e1.printStackTrace();

		
		
		}

		long id = controller.createAppointment(pid, cause, date, timeDB,
				location, status);

		if (!(id == -1)) {

			String patientName = controller.getPatientName(pid);

			SharedPreferences.Editor editor = app_settings.edit();

			editor.putString("aid", String.valueOf(id));
			
			editor.putString("patientName", patientName);
			
			editor.putString("date", date);
			
			editor.putString("time", timeDB);

			editor.commit();

		

			Calendar calendar = Calendar.getInstance();

			calendar.setTime(dateObj);

			int month = calendar.get(Calendar.MONTH);
			
			int year = calendar.get(Calendar.YEAR);
			
			int day = calendar.get(Calendar.DAY_OF_MONTH);

			int hours = calendar.get(Calendar.HOUR_OF_DAY);

			int minutes = calendar.get(Calendar.MINUTE);

			int seconds = calendar.get(Calendar.SECOND);

			/* Log.d("dateForCalender", date1.toString()); */
			Log.d("hours", String.valueOf(hours));
			
			Log.d("min", String.valueOf(minutes));
			
			Log.d("sec", String.valueOf(seconds));
			
			Log.d("month", String.valueOf(month + 1));
			
			Log.d("year", String.valueOf(year));
			
			Log.d("day", String.valueOf(day));

			// For Notification

			Calendar c2 = Calendar.getInstance();
			int priorHour = hours - 1;

			c2.set(year, month, day);

			c2.set(Calendar.HOUR_OF_DAY, priorHour);
			c2.set(Calendar.MINUTE, minutes);
			c2.set(Calendar.SECOND, seconds);

			Log.d("calender", c2.toString());

			scheduleClient.setAlarmForNotification(c2);

			String message = "Thank you for visiting our clinic your appointment is scheduled on '"
					+ date
					+ "'at  '"
					+ selectedTime
					+ "' kindly be there on time .";

			boolean success = mSender.sendSMSMessage(phoneNumber, message);

			// scheduleClient.setAlarmForNotification(c1);

			Toast.makeText(this, "Appointment Created", Toast.LENGTH_SHORT)
					.show();

			Toast.makeText(this, "Notification set", Toast.LENGTH_SHORT).show();

			Toast.makeText(
					this,
					"Message sent "
							+ (success ? "successfully" : "unsuccessfully"),
					Toast.LENGTH_SHORT).show();

			Intent i = new Intent(CreateAppointmentActivity.this, Main.class);

			startActivity(i);

		} else {

			Toast.makeText(this, "Could not create appointment",
					Toast.LENGTH_SHORT).show();

		}

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {

		case TIME_DIALOG_ID:
			/*
			 * return new TimePickerDialog(this, mTimeSetListener, hour, minute,
			 * false);
			 */
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);

		}

		return null;
	}

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker arg0, int hh, int mm) {

			timeET.setText(pad(hh) + ":" + pad(mm));
			locET.requestFocus();

		}
	};
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// c1.set(year, monthOfYear, dayOfMonth);
			mYear = year;
			mMonth = monthOfYear + 1;
			mDay = dayOfMonth;

			// d1 = dateET.getText().toString();

			dateET.setText(pad(mDay) + "/" + pad(mMonth) + "/" + mYear);

			d1 = dateET.getText().toString();

			ArrayList<String> slots = controller.getSlots(d1);

			if (slots.isEmpty()) {

				Toast.makeText(
						context,
						"No Available timmings on " + d1
								+ ". Please choose another date",
						Toast.LENGTH_LONG).show();

			}

			ArrayAdapter<String> adap = new ArrayAdapter<String>(context,
					android.R.layout.simple_list_item_1, slots);
			adap.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			timeSpinner.setAdapter(adap);

			dateET.requestFocus();

		}
	};

	public static String pad(int c) {
		String cc;
		if (c < 10) {
			cc = "0" + c;
			return cc;
		} else {
			return String.valueOf(c);
		}
	}

	@Override
	protected void onStop() {
		if (scheduleClient != null)
			scheduleClient.doUnbindService();
		super.onStop();
	}

}
